import React, { useEffect, useState } from "react"
import { List, Slider, Toast, Divider, Button, Radio, Space, Card, Empty, Grid } from 'antd-mobile'
import { SmileOutline, SmileFill } from 'antd-mobile-icons'
import { useStore4Tabs, useStore4SortFiveData, useStore4SevenStarData } from '../../store'
import TableHeader from './components/TableHeader'
import LotteryItem from './components/LotteryItem'
import ProfitAndLossInfo from './components/ProfitAndLossInfo'
import { getResultList, getOldEvenTrend, getWinTrend } from "./calculate"
import { thousandFormatter, jiaoToYuan } from '../../utils/index';
import TopTabs from '../../components/TopTabs'

import './index.less'
import { TAB_KEY_SEVEN_STAR, TAB_KEY_SORT_FIVE, TREND_TYPE_WIN_STATUS, TREND_TYPE_OLD_EVEN, TREND_TYPE_OLD_EVEN_DEFAUT_NUMBER } from "../../constants"

const DEFAULT_RANGE = [12, 26]
const MARKS_RANGE = {
    10: 10,
    12: 12,
    14: 14,
    16: 16,
    18: 18,
    20: 20,
    22: 22,
    24: 24,
    26: 26,
    28: 28,
    30: 30,
}

const getColor = (num) => {
    if (num > 7) {
        return '#cf1322'
    } else if (num > 6) {
        return '#d4380d'
    } else if (num > 5) {
        return '#d46b08'
    } else if (num > 4) {
        return '#d48806'
    } else if (num > 3) {
        return '#d4b106'
    }
}

function PageCalculate() {

    /**
     * 数据相关
     */
    //#region 
    // Tab key
    const tabKey = useStore4Tabs(state => state.key)
    // 排列五的数据
    const sortFiveData = useStore4SortFiveData(state => state.sortFiveData)
    // 七星彩的数据
    const sevenStarData = useStore4SevenStarData(state => state.sevenStarData)
    // 加工后的数据
    const [dataList, setDataList] = useState([])
    // 购买汇总数据
    const [summaryInfo, setSummaryInfo] = useState()
    // 加工后的趋势数据    
    const [trendData, setTrendData] = useState()
    // 开始分析loading
    const [loading, setLoading] = useState(false)
    //#endregion

    /**
     * 取码位数
     */
    //#region 
    const [sliceNum, setSliceNum] = useState(TREND_TYPE_OLD_EVEN_DEFAUT_NUMBER)
    //#endregion

    /**
     * 筛选条件
     */
    //#region     
    // 四位和值范围
    const [fourPlaceSumRange, setFourPlaceSumRange] = useState(DEFAULT_RANGE)
    // 同位重复开关
    const [isSamePlaceRepeatIgnore, setIsSamePlaceRepeatIgnore] = useState(true)
    // 是否查看中奖趋势 || 单双趋势
    const [isShowTrend, setIsShowTrend] = useState(false)
    //趋势类型： 1:中奖趋势 || 2:单双趋势
    const [trendType, setTrendType] = useState(TREND_TYPE_WIN_STATUS)

    //#endregion

    /**
     * 购买相关
     */
    //#region 
    // 购买契机（每期、一杀后、二杀后、三杀后）
    const [buyStart, setBuyStart] = useState(0)
    // 起始金额（1角、2角、3角）
    const [buyAmount, setBuyAmount] = useState(1)
    // 翻倍方式（1倍、翻倍、盈余）
    const [buyMultiple, setBuyMultiple] = useState(1)
    //#endregion

    // 切换tab，清空数据
    useEffect(() => {
        setDataList([])
        setIsShowTrend(false)
        setSliceNum(TREND_TYPE_OLD_EVEN_DEFAUT_NUMBER)
        setTrendData(null)
    }, [tabKey])

    // 切换趋势类型
    useEffect(() => {
        if (isShowTrend) {
            countTrend()
        }
    }, [isShowTrend, trendType])

    // 切换趋势分割位数
    useEffect(() => {
        if (isShowTrend && trendType == TREND_TYPE_OLD_EVEN) {
            countTrend()
        }
    }, [sliceNum])

    // 开始分析
    const onClick = () => {

        setLoading(true)

        setTimeout(() => {
            try {
                let data
                if (tabKey == TAB_KEY_SORT_FIVE) {// 排列五  
                    data = sortFiveData
                }
                if (tabKey == TAB_KEY_SEVEN_STAR) { // 七星彩
                    data = sevenStarData
                }
                if (data) {
                    const result = getResultList({ data, fourPlaceSumRange, isSamePlaceRepeatIgnore, buyStart, buyAmount, buyMultiple })
                    setDataList(result.resultList)
                    setSummaryInfo(result.resultFinal)
                }

            } catch (error) {
                Toast.show('计算失败，请刷新后重试！')
                console.error(error)
            }

            setLoading(false)
        });
    }

    const viewTrendToggle = () => {
        if (isShowTrend) {
            // 关闭
            setIsShowTrend(false)
        } else {
            // 打开
            setIsShowTrend(true)
        }
    }

    const countTrend = () => {
        let data
        if (tabKey == TAB_KEY_SORT_FIVE) {// 排列五  
            data = sortFiveData
        }
        if (tabKey == TAB_KEY_SEVEN_STAR) { // 七星彩
            data = sevenStarData
        }
        if (data && isShowTrend) {
            if (trendType == TREND_TYPE_WIN_STATUS) {
                const winData = getWinTrend({ data, fourPlaceSumRange, isSamePlaceRepeatIgnore })
                setTrendData(winData)
            } else if (trendType == TREND_TYPE_OLD_EVEN) {
                const oldEvendata = getOldEvenTrend({ data, sliceNum })
                setTrendData(oldEvendata)
            }
        }
    }

    return (
        <>
            <TopTabs />
            <Card title="选码条件" className="card-margin-top">
                <div className="filter-wrapper">
                    <div className="operate-lable">
                        四位和值&nbsp;
                    </div>
                    <Slider
                        min={10}
                        max={30}
                        marks={MARKS_RANGE}
                        ticks
                        range
                        value={fourPlaceSumRange}
                        onChange={value => {
                            setFourPlaceSumRange(value)
                        }}
                    />
                    <div className="operate-lable">同位重复&nbsp;</div>
                    <Radio.Group value={isSamePlaceRepeatIgnore} onChange={setIsSamePlaceRepeatIgnore}>
                        <Space direction='horizontal'>
                            <Radio value={true}>开</Radio>
                            <Radio value={false}>关</Radio>
                        </Space>
                    </Radio.Group>
                </div>
                <div className="filter-wrapper">
                    <Divider />
                    <Button size="small" color='success' onClick={viewTrendToggle}>{isShowTrend ? '关闭趋势' : '分析趋势'}</Button>
                    {
                        // 查看趋势按钮
                        trendData && <>
                            <div style={{ marginTop: "10px", marginBottom: "10px" }}>
                                <Radio.Group value={trendType} onChange={setTrendType}>
                                    <Space direction='horizontal'>
                                        <Radio value={TREND_TYPE_WIN_STATUS} icon={checked =>
                                            checked ? (
                                                <SmileFill style={{ color: 'var(--adm-color-primary)' }} />
                                            ) : (
                                                <SmileOutline style={{ color: 'var(--adm-color-weak)' }} />
                                            )
                                        }>中奖趋势</Radio>
                                        <Radio value={TREND_TYPE_OLD_EVEN} icon={checked =>
                                            checked ? (
                                                <SmileFill style={{ color: 'var(--adm-color-primary)' }} />
                                            ) : (
                                                <SmileOutline style={{ color: 'var(--adm-color-weak)' }} />
                                            )
                                        }>单双趋势</Radio>
                                    </Space>
                                </Radio.Group>
                            </div>
                            {
                                // 展示单双趋势时，支持位数选择
                                trendType == TREND_TYPE_OLD_EVEN && <>
                                    {
                                        // 排列五  
                                        (tabKey == TAB_KEY_SORT_FIVE) && <>
                                            <Radio.Group value={sliceNum} onChange={setSliceNum}>
                                                <Space direction='horizontal'>
                                                    <Radio value={3}>三位</Radio>
                                                    <Radio value={4}>四位</Radio>
                                                    <Radio value={5}>五位</Radio>
                                                </Space>
                                            </Radio.Group>
                                        </>
                                    }
                                    {
                                        // 七星彩
                                        (tabKey == TAB_KEY_SEVEN_STAR) && <>
                                            <Radio.Group value={sliceNum} onChange={setSliceNum}>
                                                <Space direction='horizontal'>
                                                    <Radio value={4}>四位</Radio>
                                                    <Radio value={7}>七位</Radio>
                                                </Space>
                                            </Radio.Group>
                                        </>
                                    }
                                </>
                            }
                        </>
                    }
                </div>
                {
                    // 趋势数据列表
                    (isShowTrend && trendData) && <div className="seven-star-trend-wrapper">
                        <div className="infos-wrapper">
                            <Divider>{trendType == TREND_TYPE_WIN_STATUS ? '中奖' : '出现'}次数</Divider>
                            <div>统计期数：{trendData.count}</div>
                            <div>起始日期：{trendData.startDate}</div>
                            <div>截止日期：{trendData.endDate}</div>
                        </div>
                        <div className="numbers-wrapper">
                            <div className="numbers-lable none-bottom">{trendType == TREND_TYPE_WIN_STATUS ? '未中' : '单'}</div>
                            <div className="numbers-list none-bottom">
                                {
                                    trendData.oldList.map((item, index) => (
                                        <div key={`old_${index}`} className={`numbers-item ${trendData.lastTimeIsSingle && index == trendData.oldList.length - 1 && 'numbers-active'}`} style={{ color: getColor(item) }}>{item}</div>
                                    ))
                                }
                            </div>
                        </div>
                        <div className="numbers-wrapper">
                            <div className="numbers-lable">{trendType == TREND_TYPE_WIN_STATUS ? '中奖' : '双'}</div>
                            <div className="numbers-list">
                                {
                                    trendData.evenList.map((item, index) => (
                                        <div key={`even_${index}`} className={`numbers-item ${!trendData.lastTimeIsSingle && index == trendData.evenList.length - 1 && 'numbers-active'}`} style={{ color: getColor(item) }}>{item}</div>
                                    ))
                                }
                            </div>
                        </div>
                        {
                            trendType == TREND_TYPE_WIN_STATUS ? <div className="times-wrapper">
                                <Divider>连开统计（未中{trendData.oldTotals}回）</Divider>
                                {
                                    Object.keys(trendData.oldTimes).map(key => (

                                        <div key={key}>连续未中【 {key} 】次，出现过【 {trendData.oldTimes[key]} 】回</div>
                                    ))
                                }
                                <Divider>连开统计（中奖{trendData.evenTotals}回）</Divider>
                                {
                                    Object.keys(trendData.evenTimes).map(key => (
                                        <div key={key}>连续中奖【 {key} 】次，出现过【 {trendData.evenTimes[key]} 】回</div>
                                    ))
                                }
                            </div> : <div className="times-wrapper">
                                <Divider>连开统计（单{trendData.oldTotals}回）</Divider>
                                {
                                    Object.keys(trendData.oldTimes).map(key => (

                                        <div key={key}>连开【 {key} 】次单，出现过【 {trendData.oldTimes[key]} 】回</div>
                                    ))
                                }
                                <Divider>连开统计（双{trendData.evenTotals}回）</Divider>
                                {
                                    Object.keys(trendData.evenTimes).map(key => (
                                        <div key={key}>连开【 {key} 】次双，出现过【 {trendData.evenTimes[key]} 】回</div>
                                    ))
                                }
                            </div>

                        }
                    </div>
                }
            </Card>
            <Card title="购买设置" className="card-margin-top">
                <div className="filter-wrapper">
                    <div className="operate-lable">购买契机&nbsp;</div>
                    <Radio.Group value={buyStart} onChange={setBuyStart}>
                        <Space direction='horizontal'>
                            <Radio value={0}>每期</Radio>
                            <Radio value={1}>一败后</Radio>
                            <Radio value={2}>二败后</Radio>
                            <Radio value={3}>三败后</Radio>
                        </Space>
                    </Radio.Group>
                </div>
                <div className="filter-wrapper">
                    <div className="operate-lable">起始金额&nbsp;</div>
                    <Radio.Group value={buyAmount} onChange={setBuyAmount}>
                        <Space direction='horizontal'>
                            <Radio value={1}>1角</Radio>
                            <Radio value={2}>2角</Radio>
                            <Radio value={3}>3角</Radio>
                        </Space>
                    </Radio.Group>
                </div>
                <div className="filter-wrapper">
                    <div className="operate-lable">翻倍方式&nbsp;</div>
                    <Radio.Group value={buyMultiple} onChange={setBuyMultiple}>
                        <Space direction='horizontal'>
                            <Radio value={1}>固定1倍</Radio>
                            <Radio value={2}>败后翻倍</Radio>
                            <Radio value={3}>败后盈利</Radio>
                        </Space>
                    </Radio.Group>
                </div>
            </Card>
            <Button className="card-margin-top" block color='primary' size='large' onClick={onClick} loading={loading}>开始分析</Button>
            {
                dataList.length > 0 ?
                    <>
                        <Card title="汇总信息" className="card-margin-top">
                            <Grid columns={2} gap={50} style={{ lineHeight: '2em' }}>
                                <Grid.Item>
                                    <Grid columns={2}>
                                        <Grid.Item>总计购买：</Grid.Item>
                                        <Grid.Item>{summaryInfo.totalBuyTimes} 期</Grid.Item>
                                        <Grid.Item>中奖次数：</Grid.Item>
                                        <Grid.Item>{summaryInfo.totalSuccessTimes} 期</Grid.Item>
                                        <Grid.Item>未中次数：</Grid.Item>
                                        <Grid.Item>{summaryInfo.totalFaildTimes} 期</Grid.Item>
                                    </Grid>
                                </Grid.Item>
                                <Grid.Item>
                                    <Grid columns={3}>
                                        <Grid.Item>支出：</Grid.Item>
                                        <Grid.Item span={2} style={{ textAlign: 'right' }}>－{thousandFormatter(jiaoToYuan(summaryInfo.totalExpense))} 元</Grid.Item>
                                        <Grid.Item>收入：</Grid.Item>
                                        <Grid.Item span={2} style={{ textAlign: 'right' }}>＋{thousandFormatter(jiaoToYuan(summaryInfo.totalIncome))} 元</Grid.Item>
                                        <Grid.Item>利润：</Grid.Item>
                                        <Grid.Item span={2} style={{ textAlign: 'right' }}>{+summaryInfo.profitAndLoss > 0 ? '＋' : '－'}{thousandFormatter(jiaoToYuan(Math.abs(summaryInfo.profitAndLoss)))} 元</Grid.Item>
                                    </Grid>
                                </Grid.Item>
                            </Grid>
                        </Card>
                        <Card title="购买详情" className="card-margin-top list-wrapper">
                            <List>
                                <List.Item>
                                    <TableHeader />
                                </List.Item>
                                {dataList.map((item, index) => (
                                    <List.Item key={`${item.lotteryDrawNum}_${index}`}>
                                        <LotteryItem item={item} />
                                        {
                                            (item.info && Object.keys(item.info).length > 0) && <ProfitAndLossInfo item={item} />
                                        }
                                    </List.Item>
                                ))}
                            </List>
                        </Card>
                    </>
                    :
                    <Empty description='等待分析' />
            }

        </>
    )
}

export default PageCalculate
